//
//  CleanHouseViewController.m
//  IndexMoveHousePage
//
//  Created by 张垚 on 16/6/13.
//  Copyright © 2016年 众杰网络. All rights reserved.
//

#import "CleanHouseViewController.h"
#import "ReuseCategoryChooseTableViewCell.h"
#import "MoveHousePushTableViewCell.h"
#import "MoveHouseAreaChooseViewController.h"
#import "LabelAndTextFieldView.h"
#import "BaseTitleNavigationBar.h"
#import "MoveHouseDescriptionTableViewCell.h"
#import "ReuseDescriptionChooseCollectionViewCell.h"
#import "SubmitMenuManager.h"
#import <TZImagePickerController/TZImagePickerController.h>
#import "SDPhotoBrowser.h"


@interface CleanHouseViewController ()<UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate, UICollectionViewDelegate, UICollectionViewDataSource, UITextViewDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate, TZImagePickerControllerDelegate,SDPhotoBrowserDelegate>

{
    
    NSString *_area3;
    NSString *_uid;
    NSString *_xxdz;
    NSString *_title;
    NSString *_ms;
    NSString *_name;
    NSString *_phone;
    NSString *_qtphone;
    NSString *_lb;
}


@property (nonatomic, strong) UITableView *tableView;
/* 标题描述 */
@property (nonatomic, strong) NSMutableArray *infoArr;
/* 占位内容 */
@property (nonatomic, strong) NSMutableArray *placeHolderArr;
/* 提交按钮 */
@property (nonatomic, strong) UIButton *submitButton;
/* 键盘高度 */
@property (nonatomic, assign) CGFloat kbHeight;
//顶部视图
@property (nonatomic, strong) BaseTitleNavigationBar *myBar;
//上传图片的collectionview
@property (nonatomic, strong) UICollectionView *imageCollectionView;
//保存图片的数组
@property (nonatomic, strong) NSMutableArray<UIImage *> *itemImageArr;
@property (nonatomic, strong) NSMutableArray<UIImage *> *submitImageArr;


@property (nonatomic, strong) NSArray *keyArr;
@property (nonatomic, strong) MBProgressHUD *hud;


@end

@implementation CleanHouseViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
}

#pragma mark - 主程序入口
- (void)viewDidLoad {
    [super viewDidLoad];
     self.automaticallyAdjustsScrollViewInsets = NO;
    /* 默认键盘高度 */
    _kbHeight = 258.0f;
    /* 数据 */
    _infoArr = @[@"服务区域", @"详细地址", @"类别", @"标题", @"描述", @"联系人", @"手机号", @"其他联系"].mutableCopy;
    _placeHolderArr = @[@"请选择位置", @"请输入地址(至少6字以上)", @"请选择搬家类别",@"请输入标题(至少8字以上)", @"", @"请输入姓名", @"请输入11位手机号", @"请输入其他联系方式"].mutableCopy;
    _itemImageArr = @[[UIImage imageNamed:@"submitPhoto"]].mutableCopy;
    
    /* 注册键盘监听通知 */
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    /* tableview */
    [self ininTableView];
    [self initNavigationBar];
    // Do any additional setup after loading the view.
}
#pragma mark - 顶部自定义视图、返回上一层级
//顶部视图
- (void)initNavigationBar {
    _myBar = [[BaseTitleNavigationBar alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 64) WithTitleStr:@"搬家"];
    [self.view addSubview:_myBar];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(back)];
    [_myBar.leftView addGestureRecognizer:tap];
}
//返回上一界面
- (void)back {
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark - 键盘监听事件
- (void)keyboardWillShow:(NSNotification *)showNotification {
    /*获取键盘高度 中英文下高度是不同的 */
    CGFloat kbHeight = [[showNotification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
    /* 将高度赋给属性 第一次默认是258 如果有改动的话 根据监听进行改动 */
    _kbHeight = kbHeight;
    
}
- (void)keyboardWillHide:(NSNotification *)hideNotification {
    // 取得键盘的动画时间，这样可以在视图上移的时候更连贯
    double duration = [[hideNotification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    [UIView animateWithDuration:duration animations:^{
        _tableView.frame = CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height - 64);
    }];
}

#pragma mark - tableView
//定义tableview
- (void)ininTableView {
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height - 64) style:UITableViewStylePlain];
    /* 滑动tableview的时候 键盘收起 */
    _tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    [self.view addSubview:_tableView];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [_tableView registerClass:[MoveHousePushTableViewCell class] forCellReuseIdentifier:NSStringFromClass([MoveHousePushTableViewCell class])];
    [_tableView registerClass:[MoveHouseDescriptionTableViewCell class] forCellReuseIdentifier:NSStringFromClass([MoveHouseDescriptionTableViewCell class])];
    [self addHeaderViewAndFooterView];
}
/* 添加header和footer */
- (void)addHeaderViewAndFooterView {
    //tableview顶部视图
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 100)];
    //collctionview
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(80, 80);
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    _imageCollectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flowLayout];
    [headerView addSubview:_imageCollectionView];
    //属性设置
    _imageCollectionView.backgroundColor = [UIColor whiteColor];
    _imageCollectionView.delegate = self;
    _imageCollectionView.dataSource = self;
    _imageCollectionView.bounces = NO;
    _imageCollectionView.showsHorizontalScrollIndicator = NO;
    
//    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:nil];
//    longPress.numberOfTouchesRequired = 1;
//    longPress.minimumPressDuration = 1;
//    [_imageCollectionView addGestureRecognizer:longPress];
    
    
    [_imageCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(headerView.mas_left).offset(10);
        make.right.equalTo(headerView.mas_right).offset(-10);
        make.height.equalTo(@90);
        make.top.equalTo(headerView.mas_top).offset(10);
    }];
    [_imageCollectionView registerClass:[ReuseDescriptionChooseCollectionViewCell class] forCellWithReuseIdentifier:NSStringFromClass([ReuseDescriptionChooseCollectionViewCell class])];
    _tableView.tableHeaderView = headerView;
    //tableview尾部视图
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 80)];
    _submitButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [footerView addSubview:_submitButton];
    [_submitButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(footerView.mas_top).offset(20);
        make.left.equalTo(footerView.mas_left).offset(40);
        make.right.equalTo(footerView.mas_right).offset(-40);
        make.height.equalTo(@50);
    }];
    _submitButton.layer.masksToBounds = YES;
    _submitButton.layer.cornerRadius = 6;
    [_submitButton setTitle:@"提交" forState:UIControlStateNormal];
    [_submitButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _submitButton.backgroundColor = [UIColor colorWithRed:212 / 255.0f green:38 / 255.0f blue:26 / 255.0f alpha:1.0];
    [_submitButton addTarget:self action:@selector(submit:) forControlEvents:UIControlEventTouchUpInside];
    _tableView.tableFooterView = footerView;
    
}

//- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
//    
////    if ([touch.view isKindOfClass:[UIButton class]]){
////        
////        return NO;
////        
////    }
////
//    NSLog(@"%@", [touch.view class]);
//    return YES;
//    
//}


/* 行数 */
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _infoArr.count;
}
/* cell创建 */
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 4) {
        MoveHouseDescriptionTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([MoveHouseDescriptionTableViewCell class])];
        cell.titleLabel.text = _infoArr[indexPath.row];
        cell.mainTextView.delegate = self;
        cell.mainTextView.text = @"请大致描述您的房间";
        cell.mainTextView.textColor = [UIColor lightGrayColor];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }else {
        MoveHousePushTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([MoveHousePushTableViewCell class])];
        cell.inputView.contextTextField.tag = indexPath.row;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.inputView.titleLabel.text = _infoArr[indexPath.row];
        cell.inputView.contextTextField.placeholder = _placeHolderArr[indexPath.row];
        cell.inputView.contextTextField.delegate = self;
        if (indexPath.row == 0 || indexPath.row == 2) {
            cell.inputView.contextTextField.userInteractionEnabled = NO;
            cell.isPush = YES;
        }else {
            cell.isPush = NO;
            if (indexPath.row == 1 || indexPath.row == 3) {
                NSRange range = {5, 8};
                NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:_placeHolderArr[indexPath.row]];
                [str addAttribute:NSForegroundColorAttributeName value:KNaviBackColor range:range];
                cell.inputView.contextTextField.attributedPlaceholder = str;
            }
        }
        return cell;
    }
}
/* 行高 */
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 4) {
        return 100;
    }else {
        return 44;
    }
}
/* cell点击事件 */
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0 || indexPath.row == 2) {
        MoveHousePushTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        MoveHouseAreaChooseViewController *areaChooseVC = [[MoveHouseAreaChooseViewController alloc] init];
        if (indexPath.row == 0) {
            areaChooseVC.categoryStr = @"区域选择";
            areaChooseVC.currentStr = cell.inputView.contextTextField.text;
            [areaChooseVC passInfoToPreviousPage:^(NSString *infoStr, NSInteger tag) {
                cell.inputView.contextTextField.text = infoStr;
                _area3 = [NSString stringWithFormat:@"%ld", (long)tag];
            }];
        }else if (indexPath.row == 2) {
            areaChooseVC.categoryStr = @"类别";
            areaChooseVC.currentStr = cell.inputView.contextTextField.text;
            [areaChooseVC passInfoToPreviousPage:^(NSString *infoStr, NSInteger tag) {
                cell.inputView.contextTextField.text = infoStr;
                _lb = [NSString stringWithFormat:@"%ld", (long)tag];
            }];
        }
        [self.navigationController pushViewController:areaChooseVC animated:YES];
    }
}




#pragma mark - collectionView
//item个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _itemImageArr.count;
}
//collctionviewCell
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    ReuseDescriptionChooseCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([ReuseDescriptionChooseCollectionViewCell class]) forIndexPath:indexPath];
    cell.descriptionImageView.image = _itemImageArr[indexPath.item];
    cell.block = ^(UILongPressGestureRecognizer *longpress){
        CGPoint point = [longpress locationInView:_imageCollectionView];
        NSIndexPath *indexPath = [_imageCollectionView indexPathForItemAtPoint:point];
        if ([_itemImageArr[indexPath.item] isEqual:[UIImage imageNamed:@"submitPhoto"]]) {
            
        }else {
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
            UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"删除图片" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
                if (_itemImageArr.count == 6 && ![_itemImageArr containsObject:[UIImage imageNamed:@"submitPhoto"]]) {
                    [_itemImageArr removeObjectAtIndex:indexPath.item];
                    [_itemImageArr addObject:[UIImage imageNamed:@"submitPhoto"]];
                }else {
                   [_itemImageArr removeObjectAtIndex:indexPath.item];
                }
                [_imageCollectionView reloadData];
            }];
            UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
            [alertController addAction:okAction];
            [alertController addAction:cancel];
            [self presentViewController:alertController animated:YES completion:nil];
        }
    };
    return cell;
}
#pragma mark - 提交上传服务器
/* 提交事件 */
- (void)submit:(UIButton *)button {
    if (_area3.length == 0) {
        [self alertMessage:@"请选择区域"];
    }else if (_xxdz.length < 6) {
        [self alertMessage:@"详细地址不得少于6个字"];
    }else if (_lb.length == 0) {
        [self alertMessage:@"请选择类别"];
    }else if (_title.length == 0) {
        [self alertMessage:@"请输入标题"];
    }else if (_ms.length == 0) {
        [self alertMessage:@"请输入描述内容"];
    }else if (_name.length == 0) {
        [self alertMessage:@"请输入姓名"];
    }else {
        if (![self valiMobile:_phone] && ![self valiMobile:_qtphone]) {
            NSMutableDictionary *submitInfoDic = [NSMutableDictionary dictionary];
            [submitInfoDic setObject:[UserInfoManager sharedManager].uid forKey:@"uid"];
            [submitInfoDic setObject:_area3 forKey:@"area3"];
            [submitInfoDic setObject:_lb forKey:@"lb"];
            [submitInfoDic setObject:_xxdz forKey:@"xxdz"];
            [submitInfoDic setObject:_title forKey:@"title"];
            [submitInfoDic setObject:_ms forKey:@"ms"];
            [submitInfoDic setObject:_name forKey:@"name"];
            [submitInfoDic setObject:_phone forKey:@"phone"];
            [submitInfoDic setObject:_qtphone forKey:@"qtphone"];
            if (_itemImageArr.count == 1) {
                [self alertMessage:@"至少上传一张图片"];
                return;
            }else {
                _submitImageArr = [NSMutableArray arrayWithArray:_itemImageArr];
                if (_itemImageArr.count == 6) {
                    
                }else {
                    [_submitImageArr removeLastObject];
                }
                _hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
                _hud.label.text = @"正在加载数据";
                _hud.backgroundView.style = MBProgressHUDBackgroundStyleSolidColor;
                _hud.animationType = MBProgressHUDAnimationZoomIn;
                [NetRequest upLoadImageArr:_submitImageArr withUrl:@"http://aizufang.hrbzjwl.com/tp/api.php/Iosapp/movedoit" withParameters:submitInfoDic progress:^(NSProgress *progress) {
                                } success:^(NSURLSessionDataTask *task, id responseObject) {
                                    if ([responseObject[@"flag"] integerValue] == 1) {                                                            _hud.label.text = @"上传成功";
                                        [_hud hideAnimated:YES afterDelay:1];
                                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)),dispatch_get_main_queue(), ^{
                                                [self back];
                                                            });
                                                        }
                                    else {
                                        _hud.label.text = @"上传失败";
                                        [_hud hideAnimated:YES afterDelay:1];
                                    }
                                } failure:^(NSURLSessionDataTask *task, NSError *error) {
                                    _hud.label.text = @"服务器异常";
                                    [_hud hideAnimated:YES afterDelay:1];
                                }];
            }
        }else {
            [self alertMessage:@"请检查联系方式"];
        }
    }
    
  
}


//手机号判断
- (NSString *)valiMobile:(NSString *)mobile{
    if (mobile.length < 11)
    {
        return @"请输入11位手机号";
    }else{
        /**
         * 移动号段正则表达式
         */
        NSString *CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";
        /**
         * 联通号段正则表达式
         */
        NSString *CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";
        /**
         * 电信号段正则表达式
         */
        NSString *CT_NUM = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$";
        NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];
        BOOL isMatch1 = [pred1 evaluateWithObject:mobile];
        NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM];
        BOOL isMatch2 = [pred2 evaluateWithObject:mobile];
        NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_NUM];
        BOOL isMatch3 = [pred3 evaluateWithObject:mobile];
        
        if (isMatch1 || isMatch2 || isMatch3) {
            return nil;
        }else{
            return @"请输入正确格式的手机号";
        }
    }
    return nil;
}
//提交表单不完整的提示信息
- (void)alertMessage:(NSString *)message {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:message preferredStyle:UIAlertControllerStyleAlert];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self dismissViewControllerAnimated:YES completion:nil];
    });
    [self presentViewController:alertController animated:YES completion:nil];
}




#pragma mark - 代理协议方法
//textField代理方法
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    if (textField.tag == 1) {
        _xxdz = textField.text;
    }else if (textField.tag == 3) {
        _title = textField.text;
    }else if (textField.tag == 5) {
        _name = textField.text;
    }else if (textField.tag == 6) {
        _phone = textField.text;
    }else if (textField.tag == 7) {
        _qtphone = textField.text;
    }
}

/* 开始编辑的时候 键盘弹起 视图上移 */
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    UIView *view = textField.superview;
    while (![view isKindOfClass:[UITableViewCell class]]) {
        view = [view superview];
    }
    UITableViewCell *cell = (UITableViewCell*)view;
    CGRect rect = [cell convertRect:cell.frame toView:self.view];
    if (rect.origin.y / 2 + rect.size.height >= self.view.frame.size.height - _kbHeight) {
        CGFloat offset = _kbHeight;
        [UIView animateWithDuration:0.25 animations:^{
            _tableView.frame = CGRectMake(0, -offset + 64, self.view.frame.size.width, self.view.frame.size.height);
        }];
    }
    return YES;
}


//textView代理方法
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView {
    UIView *view = textView.superview;
    while (![view isKindOfClass:[UITableViewCell class]]) {
        view = [view superview];
    }
    UITableViewCell *cell = (UITableViewCell*)view;
    CGRect rect = [cell convertRect:cell.frame toView:self.view];
    if (rect.origin.y / 2 + rect.size.height >= self.view.frame.size.height - _kbHeight) {
        CGFloat offset = _kbHeight;
        [UIView animateWithDuration:0.25 animations:^{
            _tableView.frame = CGRectMake(0, -offset + 64, self.view.frame.size.width, self.view.frame.size.height);
        }];
    }
    return YES;
}
//点击回车键 收回键盘
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if ([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        return NO;
    }
    return YES;
}
//开始编辑 占位符消失
- (void)textViewDidBeginEditing:(UITextView *)textView {
    if ([textView.text isEqualToString:@"请大致描述您的房间"]) {
        textView.text = @"";
    }
}

//编辑结束 占位符出现
- (void)textViewDidEndEditing:(UITextView *)textView {
    if (textView.text.length < 1) {
        textView.text = @"请大致描述您的房间";
    }else {
        _ms = textView.text;
    }
}

#pragma mark - 获取图片 

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    ReuseDescriptionChooseCollectionViewCell *cell = (ReuseDescriptionChooseCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
    if (![cell.descriptionImageView.image isEqual:[UIImage imageNamed:@"submitPhoto"]]) {
        //创建SDPhotoBrowser实例
        SDPhotoBrowser *browser = [[SDPhotoBrowser alloc] init];
        browser.sourceImagesContainerView = _imageCollectionView;
        
        if (_itemImageArr.count == 6 && ![_itemImageArr containsObject:[UIImage imageNamed:@"submitPhoto"]]) {
            browser.imageCount = _itemImageArr.count;
        }else {
            browser.imageCount = _itemImageArr.count - 1;
        }
        browser.currentImageIndex = indexPath.item;
        browser.delegate = self;
        [browser show]; // 展示图片浏览器
    }else {
        [self cellClickAction];
    }
    
}

// 返回临时占位图片（即原来的小图）

- (UIImage *)photoBrowser:(SDPhotoBrowser *)browser placeholderImageForIndex:(NSInteger)index {
    UIImage *myImage = _itemImageArr[index];
    return myImage;
}



//点击添加照片cell 调取图库或相机
- (void)cellClickAction {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *cameraAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self selectForCameraButtonClick];
    }];
    UIAlertAction *pictrueAction = [UIAlertAction actionWithTitle:@"从相册获取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self selectForAlbumButtonClick];
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alertController addAction:cameraAction];
    [alertController addAction:pictrueAction];
    [alertController addAction:cancelAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

//访问相册
-(void)selectForAlbumButtonClick
{
    NSInteger picCount;
    if (_itemImageArr.count == 6 && ![_itemImageArr containsObject:[UIImage imageNamed:@"submitPhoto"]]) {
        picCount = 0;
    }else {
        picCount = 7 - _itemImageArr.count;
    }
    TZImagePickerController *imagePC = [[TZImagePickerController alloc] initWithMaxImagesCount:picCount  delegate:self];
    [imagePC setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL en) {
        for (UIImage *image in photos) {
            [_itemImageArr insertObject:image atIndex:_itemImageArr.count - 1];
        }
        if (_itemImageArr.count >= 7) {
                [_itemImageArr removeLastObject];
                }
        [_imageCollectionView reloadData];
    }];
    [self presentViewController:imagePC animated:YES completion:nil];
//    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary])
//    {
//        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
//        picker.delegate = self;
//        picker.allowsEditing = YES;
//        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
//        [self presentViewController:picker animated:YES completion:nil];
//    }
//    else {
////        UIAlertView *alert = [[UIAlertView alloc]
////                              initWithTitle:@"访问图片库错误"
////                              message:@""
////                              delegate:nil
////                              cancelButtonTitle:@"OK!"
////                              otherButtonTitles:nil];
////        [alert show];
//        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:@"访问图片错误" preferredStyle:UIAlertControllerStyleAlert];
//        UIAlertAction *action = [UIAlertAction actionWithTitle:@"好" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//
//        }];
//        [alert addAction:action];
//        [self presentViewController:alert animated:YES completion:^{
//
//        }];
//    }
}

//访问摄像头
-(void)selectForCameraButtonClick
{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary])
    {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        picker.allowsEditing = YES;
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:picker animated:YES completion:nil];
    }
    else {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:@"不可使用照相功能" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"好" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

        }];
        [alert addAction:action];
        [self presentViewController:alert animated:YES completion:^{
            
        }];
    }
}

//图像选取器的委托方法，选完图片后回调该方法

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    [_itemImageArr insertObject:info[UIImagePickerControllerOriginalImage] atIndex:_itemImageArr.count - 1];
    if (_itemImageArr.count >= 7) {
        [_itemImageArr removeLastObject];
    }
    [_imageCollectionView reloadData];
    [picker dismissViewControllerAnimated:YES completion:^{
        
    }];
}



- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
